﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Compilation;
using System.Web.UI;
using System.Web;
using System.Security.Permissions;
using System.CodeDom;

using Microsoft.SharePoint.Utilities;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Customized version of the standard Reources expression builder. This version uses the resources stored in the hive rather than
	/// the local application resource folder. This way it's possible to use application pages without having to deploy the wsp as
	/// an application wsp; it can remain global
	/// </summary>
	[ExpressionPrefix("SPMResources")] 
	[ExpressionEditor("System.Web.UI.Design.ResourceExpressionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
	[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	public class ResourceExpressionBuilder : System.Web.Compilation.ResourceExpressionBuilder
	{
		/// <summary>
		/// Extracts the values from the expression as it's definied in the page
		/// </summary>
		/// <param name="expression"></param>
		/// <param name="propertyType"></param>
		/// <param name="context"></param>
		/// <returns></returns>
		public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
		{
			if (string.IsNullOrEmpty(expression) == true) throw new ArgumentNullException("expression");

			string[] a = expression.Split(",".ToCharArray());
			
			if (a.Length != 2)
			{
				throw new InvalidOperationException(expression + " is not a legal expression");
			}
			return new Pair(a[0].Trim(), a[1].Trim());
		}
		/// <summary>
		/// Creates the code that runs when evaluating the expression
		/// </summary>
		/// <param name="entry"></param>
		/// <param name="parsedData"></param>
		/// <param name="context"></param>
		/// <returns></returns>
		public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
		{
			Pair pair = (Pair)parsedData;
		
			return new CodeMethodInvokeExpression(
				new CodeTypeReferenceExpression(base.GetType()), "ResolveResource", 
				new CodeExpression[] { new CodePrimitiveExpression(pair.First), new CodePrimitiveExpression(pair.Second) });
		}
		/// <summary>
		/// Finds the actual resource string located in the hive folder
		/// </summary>
		/// <param name="file"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string ResolveResource(string file, string key)
		{
			string source = string.Format(null,"$Resources:{0},{1}", file,key);
			return SPUtility.GetLocalizedString(source, file, (uint)System.Threading.Thread.CurrentThread.CurrentUICulture.LCID);
		}
	}
}
